import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state: () => ({
    user: null,
    token: localStorage.getItem("token") || null,
    permissions: [],
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.user?.username || "Guest",
    hasPermission: (state) => (permission) =>
      state.permissions.includes(permission),
  },
  actions: {
    setUser(user) {
      this.user = user;
    },
    setToken(token) {
      this.token = token;
      localStorage.setItem("token", token);
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    logout() {
      this.user = null;
      this.token = null;
      this.permissions = [];
      localStorage.removeItem("token");
    },
    async login(username, password) {
      try {
        // 这里应该调用实际的登录API
        // const response = await api.login(username, password)
        // 模拟登录成功
        const mockResponse = {
          data: {
            token: "mock-token-123",
            user: { username, id: 1 },
            permissions: ["read", "write"],
          },
        };

        this.setToken(mockResponse.data.token);
        this.setUser(mockResponse.data.user);
        this.setPermissions(mockResponse.data.permissions);

        return Promise.resolve(mockResponse.data);
      } catch (error) {
        return Promise.reject(error);
      }
    },
  },
});
